package itdep.common.util;

import com.sun.facelets.FaceletContext;

import javax.faces.context.FacesContext;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

/**
 * @author Ivan Khalopik
 * @version $Revision: 4 $ $Date: 2010-06-10 13:13:16 +0000 (Thu, 10 Jun 2010) $
 */
public abstract class JSFUtils {

	public static Locale getLocale() {
		return getLocale(FacesContext.getCurrentInstance());
	}

	public static Locale getLocale(final FaceletContext context) {
		return context != null ? getLocale(context.getFacesContext()) : null;
	}

	public static Locale getLocale(final FacesContext context) {
		Locale locale = context != null ? context.getExternalContext().getRequestLocale() : null;
		return verifyLocale(locale);
	}

	public static Locale verifyLocale(Locale locale) {
		if (!getSupportedLocales().contains(locale)) {
			locale = JSFUtils.getDefaultLocale();
		}
		return locale;
	}

	public static Locale getDefaultLocale() {
		return FacesContext.getCurrentInstance().getApplication().getDefaultLocale();
	}

	public static List<Locale> getSupportedLocales() {
		Iterator<Locale> i = FacesContext.getCurrentInstance().getApplication().getSupportedLocales();
		List<Locale> list = new ArrayList<Locale>();
		while (i.hasNext()) {
			list.add(i.next());
		}
		return list;
	}

}
